// 在树中寻找指定id的节点
import {delDir} from "./file";

export const findTargetNode = ({mainId, tree}) => {
  const arr = [tree]
  
  while (arr.length) {
    const cur = arr.pop()
    if (cur.mainId === mainId) {
      return cur
    }
    cur.children && cur.children.length && arr.push(...cur.children)
  }
  return void 0
}

// 递归删除节点下所有的文件
export const deleteAllFiles = list => {
  list.forEach(item => {
    if (item.type === 2) {
      delDir({path: item.fileDir, isDeleteSelf: true})
    }
    item.children && item.children.length && deleteAllFiles(item.children)
  })
}

// 删除指定节点
export const deleteTargetNode = ({mainId, isDeleteSelf = false, tree}) => {
  try {
    const node = findTargetNode({mainId, tree})
    if (isDeleteSelf) {
      const parent = findTargetNode({mainId: node.parent, tree})
      const deleteIndex = parent.children.findIndex(child => child.mainId === mainId)
      parent.children.splice(deleteIndex, 1)
    } else {
      node.children = []
      delete node.src
      delete node.fileDir
    }
  } catch (err) {
    console.log(err)
    return false
  }
  return true
}

// 过滤节点
export function filterTree ({tree, judgeCb}) {
  return tree.filter(item => {
    item.children && item.children.length && (item.children = filterTree({tree: item.children, judgeCb}))
    return judgeCb(item)
  })
}

// 更改节点的父节点为其他的节点
export function changeNodeParent ({target, tree, newParentNode}) {
  deleteTargetNode({mainId: target.mainId, isDeleteSelf: true, tree})
  newParentNode.children = newParentNode.children || []
  newParentNode.children.push(target)
  target.parent = newParentNode.mainId
}
